#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
void Createdata()
{
	int N = 10000000;
	srand(time(0));
	const char* file = "data.txt";
	FILE* fin = fopen(file, "w");
	if (fin == NULL)
	{
		perror("fopen");
		return;
	}
	for (int i = 0;i < N;i++)
	{
		int x = rand() + i;
		fprintf(fin, "%d\n", x);
	}
	fclose(fin);
}
int Compare(const void* x1, const void* x2)
{
	return (*(int*)x1 - *(int*)x2);
}
int Readdatatofile(FILE* fout, int n, const char* file1)
{
	int x = 0;
	int* arr = (int*)malloc(sizeof(int) * n);
	if (arr == NULL)
	{
		perror("malloc");
		return 0;
	}
	int j = 0;
	for (int i = 0;i < n;i++)
	{
		if (fscanf(fout, "%d", &x) == EOF)
			break;
		arr[j++] = x;
	}
	if (j == 0)
	{
		free(arr);
		return 0;
	}
	qsort(arr, j, sizeof(int), Compare);
	FILE* fin = fopen(file1, "w");
	if (fin == NULL)
	{
		free(arr);
		perror("fopen");
		return 0;
	}
	for (int i = 0;i < j;i++)
	{
		fprintf(fin, "%d\n", arr[i]);
	}
	free(arr);
	free(fin);
	return j;
}
void Mergefile(const char* file1, const char* file2, const char* mfile)
{
	FILE* fout1 = fopen(file1, "r");
	if (fout1 == NULL)
	{
		perror("fopen");
		return;
	}
	FILE* fout2 = fopen(file2, "r");
	if (fout2 == NULL)
	{
		perror("fopen");
		return;
	}
	FILE* mfile1 = fopen(mfile, "w");
	if (mfile1 == NULL)
	{
		perror("fopen");
		return;
	}
	int x1 = 0;
	int x2 = 0;
	int ret1 = fscanf(fout1, "%d", &x1);
	int ret2 = fscanf(fout2, "%d", &x2);
	while (ret1 != EOF && ret2 != EOF)
	{
		if (x1 < x2)
		{
			fprintf(mfile, "%d\n", x1);
			ret1 = fscanf(fout1, "%d", &x1);
		}
		else
		{
			fprintf(mfile, "%d\n", x2);
			ret2 = fscanf(fout2, "%d", &x2);
		}
	}
	while (ret1 != EOF)
	{
		fprintf(mfile, "%d\n", x1);
		ret1 = fscanf(fout1, "%d", &x1);
	}
	while (ret2 != EOF)
	{
		fprintf(mfile, "%d\n", x2);
		ret2 = fscanf(fout2, "%d", &x2);
	}
	fclose(fout1);
	fclose(fout2);
	fclose(mfile);
}
int main()
{
	Createdata();
	const char* file1 = "file1.txt";
	const char* file2 = "file2.txt";
	const char* mfile = "mfile.txt";
	FILE* fout = fopen("data.txt", "r");
	if (fout == NULL)
	{
		perror("fopen");
		return 0;
	}
	int m = 1000000;
	Readdatatofile(fout, m, file1);
	Readdatatofile(fout, m, file2);
	while (1)
	{
		Mergefile(file1, file2, mfile);
		remove(file1);
		remove(file2);
		rename(mfile, file1);
		int n = 0;
		if (n = Readdatatofile(fout, m, file2) == 0)
			break;
	}
	return 0;
}